package com.deep.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deep.common.utils.PageUtils;
import com.deep.common.utils.Query;
import com.deep.common.utils.R;
import com.deep.product.dao.SkuInfoDao;
import com.deep.product.feign.SeckillFeignService;
import com.deep.product.model.dto.SeckillSkuDTO;
import com.deep.product.model.entity.SkuImagesEntity;
import com.deep.product.model.entity.SkuInfoEntity;
import com.deep.product.model.entity.SpuInfoDescEntity;
import com.deep.product.model.vo.SkuItemSaleAttrVO;
import com.deep.product.model.vo.SkuItemVO;
import com.deep.product.model.vo.SpuItemAttrGroupVO;
import com.deep.product.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuInfoDao skuInfoDao;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private SeckillFeignService seckillFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryDetail(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (StringUtils.hasLength(key)) {
            wrapper.like("sku_name", key).or();
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public SkuItemVO queryItem(Long skuId) {
        Assert.notNull(skuId, "skuId 不能为空!");
        SkuItemVO skuItemVO = new SkuItemVO();

        // ①异步
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            // 1.取sku实体
            SkuInfoEntity infoEntity = getById(skuId);
            skuItemVO.setInfo(infoEntity);
            return infoEntity;
        }, executor);

        // 等①完成后再进行
        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync(res -> {
            // 3.获取sku销售属性组合
            List<SkuItemSaleAttrVO> saleAttrVOS =
                    skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            skuItemVO.setSaleAttr(saleAttrVOS);
        }, executor);

        // 等①完成后再进行
        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync(res -> {
            // 4.获取spu介绍
            SpuInfoDescEntity spuInfo = spuInfoDescService.getById(res.getSpuId());
            skuItemVO.setDesc(spuInfo);
        }, executor);

        // 等①完成后再进行
        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync(res -> {
            // 5.获取spu规格参数信息
            List<SpuItemAttrGroupVO> attrGroups =
                    attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            skuItemVO.setGroupAttrs(attrGroups);
        }, executor);

        // ②异步
        CompletableFuture<Void> imgFuture = CompletableFuture.runAsync(() -> {
            // 2.sku图片信息
            List<SkuImagesEntity> imagesEntities = skuImagesService.getImagesBySkuId(skuId);
            skuItemVO.setImages(imagesEntities);
        }, executor);

        // 6.查询当前商品是否参与秒杀优惠
        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            R r = seckillFeignService.getSkuSeckillInfo(skuId);
            if (r.getCode() == 0) {
                SeckillSkuDTO seckillSkuDTO = r.getData("data", new TypeReference<SeckillSkuDTO>() {
                });
                if (seckillSkuDTO != null) {
                    long now = System.currentTimeMillis();
                    if (now > seckillSkuDTO.getEndTime()) {
                        skuItemVO.setSeckillSkuDTO(null);
                    }
                    skuItemVO.setSeckillSkuDTO(seckillSkuDTO);
                }
            }
        }, executor);


        // ③等待所有异步都完成后再返回
        try {
            CompletableFuture.allOf(saleAttrFuture, descFuture, baseAttrFuture, imgFuture, seckillFuture).get();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return skuItemVO;
    }

    @Override
    public BigDecimal getPriceBySkuId(Long skuId) {
        Assert.notNull(skuId, "skuId不能为空!");

        SkuInfoEntity entity = this.getById(skuId);
        if (entity != null) {
            return entity.getPrice();
        }

        return new BigDecimal(0);
    }

    @Override
    public Long getSpuIdBySkuId(Long skuId) {
        Assert.notNull(skuId, "skuId不能为空!");
        return skuInfoDao.getSpuIdBySkuId(skuId);
    }

}